#!/usr/bin/python
# -*- coding: utf-8 -*-

from distutils.core import setup
import sys, os, re
from ts2mkv import config

def askSelection(defaultSelection):
    selection = 0
    while selection < 1 or selection > counter:
            selection = raw_input('Selection [%d]: ' % (defaultSelection))
            if selection == '':
                selection = defaultSelection
            else:
                try:
                    selection = int(selection)
                    if selection < 1 or selection > counter:
                        print 'Error: Invalid selection'
                except ValueError:
                    print 'Error: Not a valid number'
    return selection

if len(sys.argv) > 1 and sys.argv[1] == 'install':
    print
    print 'Choose the default video preset:'
    print '--------------------------------'
    counter = 0
    defaultSelection = 1
    videoPresets = config.getAvailableVideoPresets()
    for preset in videoPresets:
        data = config.getPresetData(preset)
        counter += 1
        print '%d: %s' % (counter, data['name'])
        if preset == config.settings['videopreset']:
            defaultSelection = counter
    videoPreset = videoPresets[askSelection(defaultSelection) - 1]

    print
    print 'Choose the default audio preset:'
    print '--------------------------------'
    counter = 0
    defaultSelection = 1
    audioPresets = config.getAvailableAudioPresets()
    for preset in audioPresets:
        data = config.getPresetData(preset)
        counter += 1
        print '%d: %s' % (counter, data['name'])
        if preset == config.settings['audiopreset']:
            defaultSelection = counter
    audioPreset = audioPresets[askSelection(defaultSelection) - 1]

    configfile = os.path.join(config.configDir, 'config.ini')
    f = open(configfile)
    cont = f.read()
    cont = re.sub('videopreset = .*', 'videopreset = ' + videoPreset, cont)
    cont = re.sub('audiopreset = .*', 'audiopreset = ' + audioPreset, cont)
    f.close()

    print 'Writing config.ini'
    open(configfile, 'w').write(cont)
    print


projectxfiles = [('/usr/share/ts2mkv', ['ts2mkv/ProjectX.jar', 'ts2mkv/colours.tbl'])]
for d in ['ts2mkv/lib', 'ts2mkv/dll']:
    for root, dirs, files in os.walk(d):
        projectxfiles.append(('/usr/share/' + root, [os.path.join(root, f) for f in files]))

configfiles = [('/etc/ts2mkv', ['ts2mkv/config.ini', 'ts2mkv/X.ini'])]

setup(
    name='ts2mkv',
    version='0.3.0',
    author='Jaakko Vuori',
    packages=['ts2mkv',],
    scripts=['bin/ts2mkv', 'bin/mkvenc',],
    data_files=projectxfiles + configfiles,
    url='http://code.google.com/p/ts2mkv/',
    license='LICENSE.txt',
    description='Script to convert (DVB) .ts into H.264/AAC encoded mkv',
    long_description=open('README.txt').read(),
)
